#!/usr/bin/jssh

//Auxiliary
String.prototype.trim = function() 
{
    return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() 
{
    return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() 
{
    return this.replace(/\s+$/,"");
}

var alarmFlag = -1;

function showData()
{
    nc_move(0, 0);

    nc_printw("dspace v1.0\n");
    nc_printw("by p1r0\n\n");

    var ret = call("df -h | grep " + argv[1]);
    var data1 = ret.split(" ");
    var data = new Array();
    
    for(var i = 0; i < data1.length; i++)
    {
        if(data1[i] != "")
        {
            data[data.length] = data1[i];
        }
    }
    
    nc_printw("Device: " + data[0].trim() + "\n");
    nc_printw("Size: " + data[1].trim() + "\n");
    nc_printw("Used: " + data[2].trim() + "\n");
    nc_printw("Free: " + data[3].trim() + "\n");
    nc_printw("Percent: " + data[4].trim() + "\n");
    
    var iPercent = parseInt(data[4]);
    
    nc_printw("\n\n|");
    for(var i = 0; i < iPercent; i ++)
    {
        nc_printw("=");
    }
    
    for(var i = iPercent; i < 100; i ++)
    {
        nc_printw("-");
    }
    
    nc_printw("|\n\n");
    nc_printw("\n\n");
    if(iPercent >= conf.alarm)
    {
        if(alarmFlag == -1)
        {
            nc_printw("YOU HAVE LESS THAN RECOMENDED SPACE LEFT!!!\n"); 
        }
        else
        {
            nc_printw("\n"); 
        }
        alarmFlag *= -1;
    }
    nc_refresh();
    
};

if(argv.length >= 2)
{
    nc_initscr();
    
    include("conf.js");

    while(1)
    {
        showData();
        sleep(1);
    }
}
else
{
    print("Usage: dspace.js [device]\n");
}